
var app = getApp();
var interval_second = 0.03;
var interval_millisecond = interval_second * 1000;
var left_border = 0;
var right_border = 375 - 25;
var top_border = 50;
var bottom_border = 667 - 25 - 42;
Page({
    data: {
        x: 1,
        y: top_border+1,
        record_x: 0,
        record_y: 0,
        vx: 128,
        vy: 96,
        record_vx: 0,
        record_vy: 0,
        interval_id: 0,
        display_start: "none",
        display_stop: "block",
        drag_start_timestamp: 0,
    },
    onLoad: function(){
        console.log("ball page on load");
        var interval_id = setInterval(this.move, interval_millisecond);
        this.setData({
            interval_id: interval_id,
        });
    },
    onShow: function() {
        this.start;
    },
    onHide: function() {
        this.stop;
    },
    move: function move() {
        this.bounce();
        this.setData({
            x: this.data.x+this.data.vx*interval_second,
            y: this.data.y+this.data.vy*interval_second,
        });
    },
    bounce: function bounce() {
        if (left_border >= this.data.x || right_border <= this.data.x) {
            this.setData({
                vx: 0-this.data.vx,
            });
        }
        if (top_border >= this.data.y || bottom_border <= this.data.y) {
            this.setData({
                vy: 0-this.data.vy,
            });
        }
    },
    stop: function(e) {
        this.setData({
            record_x: this.data.x,
            record_y: this.data.y,
            record_vx: this.data.vx,
            record_vy: this.data.vy,
            vx: 0,
            vy: 0,
            display_start: "block",
            display_stop: "none",
        });
    },
    start: function(e) {
        this.setData({
            vx: this.data.record_vx,
            vy: this.data.record_vy,
            display_start: "none",
            display_stop: "block",
        });
    },
    drag_start: function(e) {
        this.setData({
            drag_start_timestamp: e.timeStamp,
        });
    },
    drag_move: function(e) {
        this.setData({
            x: e.touches[0].pageX,
            y: e.touches[0].pageY,
        });
    },
    drag_stop: function(e) {
        console.log(e);
        var offset_time = (e.timeStamp - this.data.drag_start_timestamp)/1000;
        var offset_x = e.changedTouches[0].pageX - this.data.record_x;
        var offset_y = e.changedTouches[0].pageY - this.data.record_y;
        this.setData({
            vx: offset_x/offset_time,
            vy: offset_y/offset_time,
            display_start: "none",
            display_stop: "block",
        });
    },
});

